var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var app = getApp();
var level = 0;
var getcardid = 0;
var wxAuthFail = true;
Page({
  data: {
    bottom_nav_data: [],
    util: util,
    version: util.version,
    token: '',
    uid: 0,
    isgeted : false,
    minHeight: 0,
    coin: 0.00,
    userinfo: {},
    cardlist: {},

    actionSheetHidden: true,

    isIphone_x: false,
    nav_bgColor: '#ffffff',
    isShow: false,

    ka_image_w: 290,

    user_jifen: 0,
    tc:1
  },
  onLoad: function (data) {
    var tc = app.get_tc();
    var that = this;
    that.setData({
      tc: tc,
    });
    var titlename = tc == 1 ? '會員卡' : '会员卡';
    wx.setNavigationBarTitle({
      title: titlename,
    })

    //获取颜色配置
    app.getColorSetData(function (color) {
      that.setData({
        colorSet: color
      })
      that.resetNavColor();
    });

    wx.showShareMenu({
      withShareTicket: true
    })
    this.setData({
      user_jifen: data.jifen
    });

    level = data.level ? data.level : 0;
    getcardid = data.cardid ? data.cardid : 0;
    console.log('******', level, getcardid)
    wx.showLoading({
      title: 'loading',
    });
    this.getLoginInfo();
    var that = this;
    console.log('data**********',data);

    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "getkastatus",
        "level": level,
        "getcardid" : getcardid
      },
      success: function (responseData) {
        console.log(responseData.data);
        if (responseData.data.isused == 1) {
          level = 0;
          getcardid = 0;
          that.setData({
            isgeted : true
          });
          console.log('此会员卡已领取过');
          wx.showToast({
            title: tc == 1 ? '此會員卡已領取過' : '此会员卡已领取过',
             icon: 'loading',
             duration: 3000
          })
        }
        
      }
    });
    
    wx.getSystemInfo({
      success: function (res) {
        var isIphone_x = (res.model.indexOf('iPhone x') >= 0);
        that.setData({
          minHeight: res.windowHeight,
          isIphone_x: isIphone_x,
          ka_image_w: res.windowWidth - 30
        });
      }
    });
  },

  getLoginInfo: function () {
    var that = this;
    app.LoginUserInfo(function (res) {
      console.log("mine login:", res);
      wxAuthFail = res == -1;//用户拒绝授权
      if (wxAuthFail) {
        return;
      }
      that.setData({
        uid: res.uid,
        token: res.token
      });

      that.getKaListData();
    });
  },

  getKaListData: function(){
    var that = this;
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "getkalist",
        "uid": that.data.uid
      },
      success: function (responseData) {
        console.log("卡列表:",responseData.data);
        var cardData= responseData.data.get;
        var cardlist= {};

        console.log("用户积分:",that.data.user_jifen);
        for(var i = 0; i <cardData.length;i++){
          if(util.orgid == '13078'){ //小甜甜
            // if(that.data.user_jifen >= 8800){ //判断积分是否满足8800
            //   cardlist.get = cardData;
            // }else if(that.data.user_jifen >= 5000){ //判断积分是否满足5000
            //   cardlist.get = cardData[1];
            // }else if(that.data.user_jifen >= 2000){ //判断积分是否满足2000
            //   cardlist.get = cardData[2];
            // }
            cardlist.get = cardData;
          }else{
            if(that.data.user_jifen > 0){ //判断积分是否满足10000
              cardlist.get = cardData;
            }
          }
        }
        console.log("卡列表2:",cardlist);
        that.setData({
          cardlist: cardlist
        });
        wx.hideLoading();
      }
    });
  },

  //重新读取 登录用户信息
  reGetUserInfo: function (e) {
    var that = this;
    console.log("reGetUserInfo: ", e);
    if (e == 1) {
      that.getLoginInfo();
    }
  },

  goAtherPage: function (e) {
    if (wxAuthFail) {
      app.reAuthorize(this.reGetUserInfo);
    } else {
      var url = e.currentTarget.dataset.link;
      wx.navigateTo({ url: url })
    }
  },
  goAtherPageRedirect: function (e) {
    var url = e.currentTarget.dataset.link;
    wx.redirectTo({ url: url })
  },

  //保存formId
  submitFormId: function (e) {
    app.saveFormId(e.detail.formId);

    var path = e.detail.value.nav_path;
    if (path) {
      wx.redirectTo({ url: path })
    }
  },


  newQuan: function (e) {
    var that = this;
    var cardid = e.currentTarget.dataset.cardid;

    if(util.orgid == '13078'){ //小甜甜
      if(cardid == "pJwxVv6Uc9SOf3c8y6ahwpf3icyg" && that.data.user_jifen < 8800){ //判断积分是否满足8800
        var contentname = this.data.tc == 1 ? '妳的積分不足8800分' : '你的积分不足8800分';
        wx.showModal({  
            title: '提示',  
            content: contentname,  
            showCancel: false,//去掉取消按钮   
        });
        return;
      }else if(cardid == "pJwxVv2HCc6qEr7Slz0QiKXtlbQI" && that.data.user_jifen < 5000){ //判断积分是否满足5000
        var contentname = this.data.tc == 1 ? '妳的積分不足5000分' : '你的积分不足5000分';
       wx.showModal({  
            title: '提示',  
            content: contentname,  
            showCancel: false,//去掉取消按钮   
        });
        return;
      }else if(cardid == "pJwxVv-pVnlmF8nkmVdMb0UCOge8" && that.data.user_jifen < 2000){ //判断积分是否满足2000
        var contentname = this.data.tc == 1 ? '妳的積分不足2000分' : '你的积分不足2000分';
        wx.showModal({  
            title: '提示',  
            content: contentname,  
            showCancel: false,//去掉取消按钮   
        });
        return;
      }
    }
console.log(e);
    console.log('*****level'+level, getcardid);
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "getka",
        "id": util.appid,
        "uid": that.data.uid,
        "cardId": e.currentTarget.dataset.cardid,
        "level": level
        //"cardId":"pD0RuwobZX56cuxKq90kSJXZVKLI",

      },
      success: function (responseData) {
        console.log(responseData);
        var signdata = responseData.data;
        var cext = '{"openid":"' + signdata.openid + '","nonce_str":"' + signdata.nonce_str + '","timestamp":"' + signdata.timestamp + '","signature":"' + signdata.signature + '"}';
        console.log(cext);
      
        wx.addCard({
          cardList: [{
            cardId: signdata.cardId,
            cardExt: '{"openid":"' + signdata.openid + '","nonce_str":"' + signdata.nonce_str + '","timestamp":"' + signdata.timestamp + '","signature":"' + signdata.signature + '"}'
          }], // 需要添加的卡券列表
          success: function (res) {
            console.log(res);
            var addinfo = res['cardList'][0]
            var datainfo = {
              "publickey": util.publiccode,
              "ac": "saveuserka",
              "appid": util.appid,
              "uid": that.data.uid,
              "cardId": addinfo.cardId,
              "code": addinfo.code,
              "cartExt": addinfo.cartExt,
              "isSuccess": addinfo.isSuccess,
              "level": level,
              "getcardid": getcardid,
              "privatekey": utilMd5.hexMD5(that.data.uid + 'saveuserka' + that.data.token)

            }
            console.log(datainfo);
            util.api({
              method: "post",
              data: datainfo,
              success: function (responseData) {
                console.log(responseData)
              }
            });
            console.log("你成功领取了会员卡！");
          },
          cancel: function (res) {
            console.log(level, getcardid)
            console.log(res)
            console.log('已取消')
          },
          fail: function (res) {
            console.log(res)
            console.log("失败")

          }
        });
      }
    });
  },

  showEWM: function (e) {
    var imgurl = e.currentTarget.dataset.imgsrc;
    console.log("图片链接：" + imgurl);
    wx.previewImage({
      current: imgurl,
      urls: [imgurl]
    })
  },
  resetNavColor: function () {
    var bg_color = '#d8202d';
    var fg_color = '#ffffff';
    if (this.data.colorSet) {
      var colorJO = this.data.colorSet;
      bg_color = colorJO.titlebg;
      fg_color = colorJO.titlefont;
    }
    wx.setNavigationBarColor({
      frontColor: fg_color,
      backgroundColor: bg_color
    })
  },
})
